'''
    NASA Jpl's Boxee plugin
'''

__plugin__ = "NASA Jpl"
__author__ = "flynnguy" 

import urllib, urllib2, re, os, feedparser
import xbmcplugin, xbmcgui 

def index(url):
    '''
        Pulls RSS feed and generates list of links.
    '''
    d = feedparser.parse(url)
    for entry in d['entries']:
        info = [entry.updated, entry.subtitle, entry.image.href]
        print entry.link
        addLink(entry.title.replace('Video: ',''), entry.link, info)

def get_params():
    param=[]
    paramstring=sys.argv[2]
    if len(paramstring)>=2:
        params=sys.argv[2]
        cleanedparams=params.replace('?','')
        if (params[len(params)-1]=='/'):
            params=params[0:len(params)-2]
        pairsofparams=cleanedparams.split('&')
        param={}
        for i in range(len(pairsofparams)):
            splitparams={}
            splitparams=pairsofparams[i].split('=')
            if (len(splitparams))==2:
                param[splitparams[0]]=splitparams[1]
    return param

def addLink(name,url,info):
    """ Add a Link to video file """
    ok=True
    liz=xbmcgui.ListItem(name, iconImage=info[2], thumbnailImage=info[2])
    liz.setInfo( type="Video", infoLabels={ "Title": name, "Date": info[0], "Plot": info[1] } )
    ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
    return ok


def addDir(name,url,mode,iconimage):
    """ Used to create a navigation type link """
    # Not used in this file but saved for future reference
    u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
    ok=True
    liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
    liz.setInfo( type="Video", infoLabels={ "Title": name } )
    ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
    return ok
        
              
params=get_params()
url='http://www.jpl.nasa.gov/multimedia/rss/podfeed-hd.xml'
name='NASA Jpl'
mode=None

try:
    url=urllib.unquote_plus(params["url"])
    name=urllib.unquote_plus(params["name"])
    mode=int(params["mode"])
except:
    pass

print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)

if mode==None or url==None or len(url)<1:
    url='http://www.jpl.nasa.gov/multimedia/rss/podfeed-hd.xml'
    index(url)
elif mode==1:
    index(url)
elif mode==2:
    videolinks(url,name)

xbmcplugin.endOfDirectory(int(sys.argv[1]))

